/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imp.reciever.input;

import dom.Command;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
 * @author julian.pena
 */
public class ReadFolder extends InputReciever{

    private File directory;
    
    public ReadFolder(File directory) throws Exception {
        super(null);
        if (!directory.isDirectory()) {
            throw new Exception("In not a folder");
        }
        this.directory = directory;
    }
    
    public ReadFolder(String path) throws Exception {
        super(null);
        File directory = new File(path);
        if (!directory.isDirectory()) {
            throw new Exception("In not a folder");
        }
        this.directory = directory;
    }

    public ReadFolder(FileInputStream inputStream, Command command) {
        super(inputStream, command);
    }

    @Override
    public void action() throws FileNotFoundException, IOException {
        String absolutePath = directory.getAbsolutePath();
        String[] files = directory.list();
        byte[] buf = new byte[BUFFER_SIZE];
        for (String string : files) {
            File file = new File(absolutePath + SEPARATOR + string);
            if (!file.isFile()) {
                continue;
            }
            System.out.println("leyendo: " + file.getAbsolutePath());
            super.notifyStop(absolutePath + SEPARATOR + string);
            inputStream = new FileInputStream(file);
            int len;
            while ((len = inputStream.read(buf)) > 0) { 
                outputStream.write(buf, 0, len); 
            }
            inputStream.close();
        }
        System.out.println("termino de leer la carpeta: " + absolutePath);
        super.notifyStop(null);
        outputStream.close();
    }

    @Override
    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    @Override
    public boolean isOutputReady() {
        if (outputStream != null) {
            return true;
        } else {
            return false;
        }
    }
}
